"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  useProjects,
  useCreateProject,
  useUpdateProject,
} from "@/modules/project";
import { Project, ProjectCreate, ProjectUpdate } from "@/modules/project/types";
import { toast } from "sonner";
import { Plus, Search, Edit } from "lucide-react";

export default function ProjectsPage() {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    page_size: 10,
    project_number: "",
    project_type: "",
    status: "",
  });

  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);

  const [newProject, setNewProject] = useState<
    Omit<ProjectCreate, "start_date" | "end_date">
  >({
    project_number: "",
    project_type: "",
    funding_amount: 0,
    status: "",
  });

  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [editForm, setEditForm] = useState<
    Omit<ProjectUpdate, "id" | "start_date" | "end_date">
  >({
    project_number: "",
    project_type: "",
    funding_amount: 0,
    status: "",
  });

  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [editStartDate, setEditStartDate] = useState("");
  const [editEndDate, setEditEndDate] = useState("");

  const { data: projectsData, isLoading, error } = useProjects(searchParams);
  const { createProject, creating } = useCreateProject();
  const { updateProject, updating } = useUpdateProject();

  const handleSearch = () => {
    setSearchParams((prev) => ({ ...prev }));
  };

  const handleCreateProject = async () => {
    try {
      const projectData: ProjectCreate = {
        ...newProject,
        start_date: startDate,
        end_date: endDate,
      };

      await createProject(projectData);
      toast.success("项目创建成功");
      setIsCreateDialogOpen(false);
      // 重置表单
      setNewProject({
        project_number: "",
        project_type: "",
        funding_amount: 0,
        status: "",
      });
      setStartDate("");
      setEndDate("");
    } catch (error) {
      toast.error("创建项目失败");
      console.error(error);
    }
  };

  const handleEditProject = async () => {
    if (!editingProject) return;

    try {
      const projectData: ProjectUpdate = {
        id: editingProject.id,
        ...editForm,
        start_date: editStartDate,
        end_date: editEndDate,
      };

      await updateProject(projectData);
      toast.success("项目更新成功");
      setIsEditDialogOpen(false);
      // 重置表单
      setEditingProject(null);
      setEditForm({
        project_number: "",
        project_type: "",
        funding_amount: 0,
        status: "",
      });
      setEditStartDate("");
      setEditEndDate("");
    } catch (error) {
      toast.error("更新项目失败");
      console.error(error);
    }
  };

  const openEditDialog = (project: Project) => {
    setEditingProject(project);
    setEditForm({
      project_number: project.project_number,
      project_type: project.project_type,
      funding_amount: project.funding_amount,
      status: project.status,
    });
    setEditStartDate(project.start_date.split("T")[0]); // 提取日期部分
    setEditEndDate(project.end_date.split("T")[0]); // 提取日期部分
    setIsEditDialogOpen(true);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString();
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">项目管理</h1>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              新建项目
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle>创建新项目</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="project_number">项目号</Label>
                <Input
                  id="project_number"
                  value={newProject.project_number}
                  onChange={(e) =>
                    setNewProject({
                      ...newProject,
                      project_number: e.target.value,
                    })
                  }
                  placeholder="请输入项目号"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="project_type">项目类型</Label>
                <Input
                  id="project_type"
                  value={newProject.project_type}
                  onChange={(e) =>
                    setNewProject({
                      ...newProject,
                      project_type: e.target.value,
                    })
                  }
                  placeholder="请输入项目类型"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="funding_amount">资助金额</Label>
                <Input
                  id="funding_amount"
                  type="number"
                  value={newProject.funding_amount}
                  onChange={(e) =>
                    setNewProject({
                      ...newProject,
                      funding_amount: Number(e.target.value),
                    })
                  }
                  placeholder="请输入资助金额"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="start_date">开始时间</Label>
                <Input
                  id="start_date"
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="end_date">结束时间</Label>
                <Input
                  id="end_date"
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="status">当前状态</Label>
                <Input
                  id="status"
                  value={newProject.status}
                  onChange={(e) =>
                    setNewProject({ ...newProject, status: e.target.value })
                  }
                  placeholder="请输入当前状态"
                />
              </div>
              <div className="flex justify-end space-x-2">
                <Button
                  variant="outline"
                  onClick={() => setIsCreateDialogOpen(false)}
                >
                  取消
                </Button>
                <Button onClick={handleCreateProject} disabled={creating}>
                  {creating ? "创建中..." : "创建"}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>项目列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex flex-wrap gap-4">
              <div className="flex-1 min-w-[200px]">
                <Label htmlFor="search_project_number">项目号</Label>
                <Input
                  id="search_project_number"
                  value={searchParams.project_number}
                  onChange={(e) =>
                    setSearchParams({
                      ...searchParams,
                      project_number: e.target.value,
                    })
                  }
                  placeholder="搜索项目号"
                />
              </div>
              <div className="flex-1 min-w-[200px]">
                <Label htmlFor="search_project_type">项目类型</Label>
                <Input
                  id="search_project_type"
                  value={searchParams.project_type}
                  onChange={(e) =>
                    setSearchParams({
                      ...searchParams,
                      project_type: e.target.value,
                    })
                  }
                  placeholder="搜索项目类型"
                />
              </div>
              <div className="flex-1 min-w-[200px]">
                <Label htmlFor="search_status">状态</Label>
                <Input
                  id="search_status"
                  value={searchParams.status}
                  onChange={(e) =>
                    setSearchParams({ ...searchParams, status: e.target.value })
                  }
                  placeholder="搜索状态"
                />
              </div>
              <div className="self-end">
                <Button onClick={handleSearch} className="w-full">
                  <Search className="mr-2 h-4 w-4" />
                  搜索
                </Button>
              </div>
            </div>

            {isLoading && <div>加载中...</div>}
            {error && (
              <div className="text-red-500">加载数据失败: {error.message}</div>
            )}

            {projectsData && (
              <>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>项目号</TableHead>
                      <TableHead>项目类型</TableHead>
                      <TableHead>资助金额</TableHead>
                      <TableHead>开始时间</TableHead>
                      <TableHead>结束时间</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {projectsData.record_list.map((project) => (
                      <TableRow key={project.id}>
                        <TableCell>{project.project_number}</TableCell>
                        <TableCell>{project.project_type}</TableCell>
                        <TableCell>{project.funding_amount}</TableCell>
                        <TableCell>{formatDate(project.start_date)}</TableCell>
                        <TableCell>{formatDate(project.end_date)}</TableCell>
                        <TableCell>{project.status}</TableCell>
                        <TableCell>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => openEditDialog(project)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>

                {projectsData.record_list.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无项目数据
                  </div>
                )}
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 编辑项目对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>编辑项目</DialogTitle>
          </DialogHeader>
          {editingProject && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="edit_project_number">项目号</Label>
                <Input
                  id="edit_project_number"
                  value={editForm.project_number}
                  onChange={(e) =>
                    setEditForm({ ...editForm, project_number: e.target.value })
                  }
                  placeholder="请输入项目号"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_project_type">项目类型</Label>
                <Input
                  id="edit_project_type"
                  value={editForm.project_type}
                  onChange={(e) =>
                    setEditForm({ ...editForm, project_type: e.target.value })
                  }
                  placeholder="请输入项目类型"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_funding_amount">资助金额</Label>
                <Input
                  id="edit_funding_amount"
                  type="number"
                  value={editForm.funding_amount}
                  onChange={(e) =>
                    setEditForm({
                      ...editForm,
                      funding_amount: Number(e.target.value),
                    })
                  }
                  placeholder="请输入资助金额"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_start_date">开始时间</Label>
                <Input
                  id="edit_start_date"
                  type="date"
                  value={editStartDate}
                  onChange={(e) => setEditStartDate(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_end_date">结束时间</Label>
                <Input
                  id="edit_end_date"
                  type="date"
                  value={editEndDate}
                  onChange={(e) => setEditEndDate(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit_status">当前状态</Label>
                <Input
                  id="edit_status"
                  value={editForm.status}
                  onChange={(e) =>
                    setEditForm({ ...editForm, status: e.target.value })
                  }
                  placeholder="请输入当前状态"
                />
              </div>
              <div className="flex justify-end space-x-2">
                <Button
                  variant="outline"
                  onClick={() => setIsEditDialogOpen(false)}
                >
                  取消
                </Button>
                <Button onClick={handleEditProject} disabled={updating}>
                  {updating ? "更新中..." : "更新"}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
